use web_sys::Storage;
use serde::{de, ser};

pub struct LocalStorage;

impl LocalStorage {

    /// 得到 LocalStorage 对象
    fn local_storage() -> Option<Storage> {
        let window = if let Some(v) = web_sys::window() { v } else {
            return None;
        };
        if let Ok(v) = window.local_storage() { v }  else {
            None
        }
    }

    /// 保存数据到localStorage
    pub fn set<T: ser::Serialize>(key: &str, data: &T) -> bool {
        let storage = if let Some(v) = Self::local_storage() { v } else {
            return false;
        };
        let value = if let Ok(v) = serde_json::to_string(data) { v } else {
            return false;
        };
        if let Ok(_) = storage.set(key, &value) { true } else { false }
    }

    /// 以对象方式获取数据
    pub fn get<T: de::DeserializeOwned>(key: &str) -> Option<T> {
        let storage = if let Some(v) = Self::local_storage() { v } else {
            return None;
        };
        let value = if let Ok(v) = storage.get(key) {
            if let Some(v) = v { v } else { return None; }
        } else {
            return None;
        };
        let result: T = if let Ok(v) = serde_json::from_str(&value) { v } else {
            return None;
        };
        Some(result)
    }
}